<?php
namespace app\common\JsonDb;

/**
 * 本地json文件处理类，减小服务器直接操作数据库的压力，实现简单的增、删、改、查
 * php >= 5.4
 * 主键: id
 */
class JsonDb {

	private $file_url;    //json文件全路径
	private $json_str;    //json字符串
	private $data_arr;    //解析json后的数组

	/**
	* 初始化
	* @param   string    $file_url      json文件全路径           
	*/
	public function __construct($file_url){
		if (is_file($file_url)) {
			$this->file_url = $file_url;
			$this->json_str = file_get_contents($file_url);
			$this->data_arr = json_decode($this->json_str, true);
		}
	}

	/**
	* 查询操作
	* @param   array     $condition   条件数组
	* $condition['key']:要查询的字段
	* $condition['keyword']:进行模糊搜索的关键字
	* $condition['value']:进行完全匹配搜索的值
	* $condition['field']:要排序的字段
	* $condition['order']:升序或逆序
	* 例：$condition=['key'=>'id','value'=>2,'field'=>'age','order'=>'DESC']
	* 模糊搜索： $condition=['key'=>'title','keyword'=>'天气',field'=>'age','order'=>'DESC']
	* @param   string    $keyword     模糊搜索的关键字
	* @param   string    $field       要排序的字段
	* @param   string    $order       默认为升序，输入：DESC或desc或SORT_DESC为逆序排序
	* @return  array   
	*/
	public function select($condition=''){
		$data_arr = $this->data_arr;
		if (empty($data_arr)) {
			return false;
		}
		if (!empty($condition)) {
			$result_arr = array(); //将要返回的数组
			if ( !empty($condition['key']) ) {
				if ( !empty($condition['value']) ) {
					foreach ($data_arr as $val) {
						if ($val[$condition['key']] == $condition['value']) {
							$result_arr[] = $val;
						}
					}
				}elseif ( !empty($condition['keyword']) ) {
					foreach ($data_arr as $val) {
						if (stristr($val[$condition['key']], $condition['keyword'])) {
							$result_arr[] = $val;
						}
					}
					if (count($result_arr) == 0) {
						return false;
					}
				}
			}else {
				$result_arr = $data_arr;
			}
			
			if ( !empty($condition['field']) ) {
				$order = 'SORT_ASC';
				if ( !empty($condition['order']) ) {
					$order = $condition['order'];
				}
				$result_arr = $this->sortArr($result_arr,$condition['field'],$order);
			}
			return $result_arr;
			
		}else {
			return $data_arr;
		}
	}

	/**
 	 * 查询单条数据
 	 * @param   array     $condition   条件数组
	 * $condition['key']:要查询的字段
	 * $condition['value']:要查询的字段的值
 	 * @return  array
 	 */
	public function find($condition=false){
		if (is_array($condition)) {
			if (!empty($condition['key']) && !empty($condition['value'])) {
				$result_arr = $this->select($condition);
				if (count($result_arr)) {
					return $result_arr[0];
				}
			}
		}
	}

	/**
	* 添加操作
	* @return  bool   
	*/
	public function insert($array){
		if (is_array($array)) {
			$data_arr = array();
			if (!empty($this->data_arr)) {
				$data_arr = $this->data_arr;
				//如果元素大于1, 新添加的数据可能缺少某些键值对，安全起见就设置为空
				$end_arr = end($data_arr);
				if (!empty($end_arr['id'])) {
					$array['id'] = $end_arr['id']+1;
				}
				foreach ($end_arr as $key => $value) {
					if (!isset($array[$key])) {
						if (is_int($value)) {
							$array[$key] = 0;
						}else {
							$array[$key] = '';
						}
					}
				}
			}else {
				//如果以前没有数据，自动设置主键 id = 1
				if (!isset($array['id'])) {
					$array['id'] = 1;
				}
			}
			$data_arr[] = $array;
			
			$str = json_encode($data_arr, JSON_UNESCAPED_UNICODE); //UTF-8 编码解码，php >= 5.4
			$check_arr =  json_decode($str, true); //为安全起见，该数组用来验证新增数据后是否能够成功解析出来
			if (is_array($check_arr)) {
				return file_put_contents($this->file_url, $str);
			}
		}
	}

	/**
	* 修改操作
	* @param   array  $data       要修改的数据数组
	* @param   array  $condition  条件数组
	* $condition['key']:    要修改的数据(用来确定范围)字段名称，比如要修改 id=2的数据：$condition['key']='id',$condition['value']=2
	* $condition['value']: 就是$condition['key']对应的值
	* @return  bool   
	*/
	public function update($data,$condition=''){
		$data_arr = $this->data_arr;
		$new_arr = array();
		if (!empty($data) && !empty($condition)) {
			if ( isset($condition['key']) && isset($condition['value']) ) {
				foreach ($data_arr as $val) {
					if ($val[$condition['key']] == $condition['value']) {
						$cur_arr = $val;
						foreach ($cur_arr as $key => $value) {
							if (!isset($data[$key])) {
								$data[$key] = $value;
							}
						}
						$new_arr[] = $data;
					}else {
						$new_arr[] = $val;
					}
				}
				$str = json_encode($new_arr, JSON_UNESCAPED_UNICODE); //UTF-8 编码解码，php >= 5.4
				$check_arr =  json_decode($str, true); //为安全起见，该数组用来验证新增数据后是否能够成功解析出来
				if (is_array($check_arr)) {
					return file_put_contents($this->file_url, $str);
				}
			}
		}elseif (!empty($data)) {
			$new_arr = $data;
			$str = json_encode($new_arr, JSON_UNESCAPED_UNICODE); //UTF-8 编码解码，php >= 5.4
			$check_arr =  json_decode($str, true); //为安全起见，该数组用来验证新增数据后是否能够成功解析出来
			if (is_array($check_arr)) {
				return file_put_contents($this->file_url, $str);
			}
		}
	}

	/**
	* 删除操作
	* @param   array  $condition  条件数组
	* $condition['key']:要删除的数据(用来确定范围)字段名称，比如要删除 id=2的数据：$condition['key']='id',$condition['value']=2
	* $condition['value']:就是$condition['key']对应的值
	* @return  bool   
	*/
	public function delete($condition){
		if (is_array($condition)) {
			$data_arr = $this->data_arr;
			if (!empty($condition['key']) && !empty($condition['value'])) {
				$new_arr = array();
				foreach ($data_arr as $val) {
					if ($val[$condition['key']] != $condition['value']) {
						$new_arr[] = $val;
					}
				}
				$str = json_encode($new_arr, JSON_UNESCAPED_UNICODE); //UTF-8 编码解码，php >= 5.4
				$check_arr =  json_decode($str, true);
				if (is_array($check_arr)) {
					return file_put_contents($this->file_url, $str);
				}
			}
		}
	}

	/**
     * 给二维数组排序
     * @param   array     $array  要排序的数组
     * @param   string    $field  字段
     * @param   string    $order  排序规则：  'ASC' 升序;  'DESC' 逆序， 默认升序
     * @return  array
     */
    protected function sortArr($array,$field,$order='SORT_ASC'){
    	if ($order == 'ASC' || $order == 'asc') {
    		$order = 'SORT_ASC';
    	}
        if ($order == 'DESC' ||  $order =='desc' || $order =='SORT_DESC') {
            $order = 'SORT_DESC';
        }
        $arrSort = array(); 
        foreach($array AS $uniqid => $row){  
            foreach($row AS $key=>$value){  
                $arrSort[$key][$uniqid] = $value;  
            }  
        }

        array_multisort($arrSort[$field], constant($order), $array);
        return $array;
    }

}